#!/bin/bash

# 舞蹈世界微服务架构自动化设置脚本
# 使用方法: chmod +x setup-microservices.sh && ./setup-microservices.sh

echo "🚀 开始设置舞蹈世界微服务架构..."

# 创建项目根目录
PROJECT_ROOT="dance-world-microservices"
mkdir -p $PROJECT_ROOT
cd $PROJECT_ROOT

echo "📁 创建项目目录结构..."

# 创建微服务目录
mkdir -p dw-common/{dw-common-core,dw-common-security,dw-common-web,dw-common-feign}
mkdir -p dw-gateway
mkdir -p dw-user-service/src/main/{java/com/example/dw/user/{controller,service/{impl},mapper,entity,dto,config,utils},resources}
mkdir -p dw-course-service/src/main/{java/com/example/dw/course/{controller,service/{impl},mapper,entity,dto,config},resources}
mkdir -p dw-activity-service/src/main/{java/com/example/dw/activity/{controller,service/{impl},mapper,entity,dto,config},resources}
mkdir -p dw-exam-service/src/main/{java/com/example/dw/exam/{controller,service/{impl},mapper,entity,dto,config},resources}
mkdir -p dw-order-service/src/main/{java/com/example/dw/order/{controller,service/{impl},mapper,entity,dto,config},resources}
mkdir -p dw-content-service/src/main/{java/com/example/dw/content/{controller,service/{impl},mapper,entity,dto,config},resources}
mkdir -p dw-portal-service/src/main/{java/com/example/dw/portal/{controller,service/{impl},client,dto,config},resources}
mkdir -p dw-admin-service/src/main/{java/com/example/dw/admin/{controller,service/{impl},client,dto,config},resources}

# 创建API定义目录
mkdir -p dw-api/{dw-user-api,dw-course-api,dw-activity-api,dw-exam-api,dw-order-api,dw-content-api}

# 创建其他目录
mkdir -p sql docs k8s scripts

echo "📄 创建配置文件..."

# 创建父POM文件
cat > pom.xml << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>dance-world-microservices</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>dw-common</module>
        <module>dw-gateway</module>
        <module>dw-user-service</module>
        <module>dw-course-service</module>
        <module>dw-activity-service</module>
        <module>dw-exam-service</module>
        <module>dw-order-service</module>
        <module>dw-content-service</module>
        <module>dw-portal-service</module>
        <module>dw-admin-service</module>
    </modules>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        
        <spring-boot.version>3.2.10</spring-boot.version>
        <spring-cloud.version>2023.0.0</spring-cloud.version>
        <spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
        <mybatis-plus.version>3.5.7</mybatis-plus.version>
        <hutool.version>5.8.22</hutool.version>
        <jwt.version>4.4.0</jwt.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
                <version>${mybatis-plus.version}</version>
            </dependency>
            
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>${hutool.version}</version>
            </dependency>
            
            <dependency>
                <groupId>com.auth0</groupId>
                <artifactId>java-jwt</artifactId>
                <version>${jwt.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                    <release>21</release>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
EOF

# 创建Docker Compose文件
cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  # MySQL
  mysql:
    image: mysql:8.0
    container_name: mysql
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=nacos
    volumes:
      - ./sql:/docker-entrypoint-initdb.d
      - mysql_data:/var/lib/mysql
    command: --default-authentication-plugin=mysql_native_password

  # Redis
  redis:
    image: redis:7.0
    container_name: redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data

  # Nacos
  nacos:
    image: nacos/nacos-server:v2.3.0
    container_name: nacos
    ports:
      - "8848:8848"
      - "9848:9848"
    environment:
      - PREFER_HOST_MODE=hostname
      - MODE=standalone
      - SPRING_DATASOURCE_PLATFORM=mysql
      - MYSQL_SERVICE_HOST=mysql
      - MYSQL_SERVICE_PORT=3306
      - MYSQL_SERVICE_DB_NAME=nacos
      - MYSQL_SERVICE_USER=root
      - MYSQL_SERVICE_PASSWORD=root
      - NACOS_AUTH_ENABLE=true
    depends_on:
      - mysql
    volumes:
      - nacos_data:/home/nacos/data

  # Zipkin
  zipkin:
    image: openzipkin/zipkin:latest
    container_name: zipkin
    ports:
      - "9411:9411"

volumes:
  mysql_data:
  redis_data:
  nacos_data:
EOF

# 创建数据库初始化脚本
cat > sql/init-databases.sql << 'EOF'
-- 创建各个微服务的数据库
CREATE DATABASE IF NOT EXISTS dw_user_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE IF NOT EXISTS dw_course_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE IF NOT EXISTS dw_activity_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE IF NOT EXISTS dw_exam_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE IF NOT EXISTS dw_order_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE IF NOT EXISTS dw_content_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

-- 创建用户并授权
CREATE USER IF NOT EXISTS 'dw_user'@'%' IDENTIFIED BY 'dw_password';
GRANT ALL PRIVILEGES ON dw_user_db.* TO 'dw_user'@'%';
GRANT ALL PRIVILEGES ON dw_course_db.* TO 'dw_user'@'%';
GRANT ALL PRIVILEGES ON dw_activity_db.* TO 'dw_user'@'%';
GRANT ALL PRIVILEGES ON dw_exam_db.* TO 'dw_user'@'%';
GRANT ALL PRIVILEGES ON dw_order_db.* TO 'dw_user'@'%';
GRANT ALL PRIVILEGES ON dw_content_db.* TO 'dw_user'@'%';

FLUSH PRIVILEGES;
EOF

# 创建用户服务POM
cat > dw-user-service/pom.xml << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>com.example</groupId>
        <artifactId>dance-world-microservices</artifactId>
        <version>1.0.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    
    <artifactId>dw-user-service</artifactId>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
        </dependency>
        
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
EOF

# 创建用户服务启动类
cat > dw-user-service/src/main/java/com/example/dw/user/UserServiceApplication.java << 'EOF'
package com.example.dw.user;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.example.dw.user.mapper")
public class UserServiceApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}
EOF

# 创建用户服务配置文件
cat > dw-user-service/src/main/resources/bootstrap.yml << 'EOF'
spring:
  application:
    name: dw-user-service
  profiles:
    active: dev
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        namespace: dw-microservices
      config:
        server-addr: localhost:8848
        namespace: dw-microservices
        file-extension: yml
        group: DEFAULT_GROUP
EOF

cat > dw-user-service/src/main/resources/application.yml << 'EOF'
server:
  port: 8081

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dw_user_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: dw_user
    password: dw_password
  
  data:
    redis:
      host: localhost
      port: 6379
      database: 1

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-aliases-package: com.example.dw.user.entity

jwt:
  secret: dw-user-service-secret-key
  expiration: 86400000

management:
  endpoints:
    web:
      exposure:
        include: "*"
EOF

# 创建网关POM
cat > dw-gateway/pom.xml << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>com.example</groupId>
        <artifactId>dance-world-microservices</artifactId>
        <version>1.0.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    
    <artifactId>dw-gateway</artifactId>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
            </plugin>
        </plugins>
    </build>
</project>
EOF

# 创建启动脚本
cat > scripts/start-all.sh << 'EOF'
#!/bin/bash

echo "🚀 启动所有微服务..."

# 启动基础设施
echo "📦 启动基础设施 (MySQL, Redis, Nacos, Zipkin)..."
docker-compose up -d

echo "⏳ 等待基础设施启动..."
sleep 30

# 启动各个微服务
echo "🔧 启动用户服务..."
cd dw-user-service && mvn spring-boot:run > ../logs/user-service.log 2>&1 &

echo "📚 启动课程服务..."
cd ../dw-course-service && mvn spring-boot:run > ../logs/course-service.log 2>&1 &

echo "🎭 启动活动服务..."
cd ../dw-activity-service && mvn spring-boot:run > ../logs/activity-service.log 2>&1 &

echo "📝 启动考试服务..."
cd ../dw-exam-service && mvn spring-boot:run > ../logs/exam-service.log 2>&1 &

echo "💰 启动订单服务..."
cd ../dw-order-service && mvn spring-boot:run > ../logs/order-service.log 2>&1 &

echo "📰 启动内容服务..."
cd ../dw-content-service && mvn spring-boot:run > ../logs/content-service.log 2>&1 &

echo "🏠 启动聚合服务..."
cd ../dw-portal-service && mvn spring-boot:run > ../logs/portal-service.log 2>&1 &

echo "🛡️ 启动网关服务..."
cd ../dw-gateway && mvn spring-boot:run > ../logs/gateway.log 2>&1 &

echo "✅ 所有服务启动完成！"
echo "🌐 访问地址:"
echo "   - Nacos控制台: http://localhost:8848/nacos"
echo "   - API网关: http://localhost:8080"
echo "   - Zipkin: http://localhost:9411"
EOF

# 创建停止脚本
cat > scripts/stop-all.sh << 'EOF'
#!/bin/bash

echo "🛑 停止所有微服务..."

# 停止Java进程
pkill -f "spring-boot:run"

# 停止Docker容器
docker-compose down

echo "✅ 所有服务已停止！"
EOF

# 创建日志目录
mkdir -p logs

# 设置脚本权限
chmod +x scripts/*.sh

echo "✅ 微服务架构设置完成！"
echo ""
echo "📋 接下来的步骤:"
echo "1. 启动基础设施: docker-compose up -d"
echo "2. 等待Nacos启动完成"
echo "3. 复制原项目的代码到对应的微服务中"
echo "4. 修改包名和依赖引用"
echo "5. 启动各个微服务"
echo ""
echo "📚 详细文档请查看:"
echo "- MICROSERVICE_ARCHITECTURE_DESIGN.md"
echo "- MIGRATION_STEP_BY_STEP.md"
echo ""
echo "🚀 快速启动: ./scripts/start-all.sh"
echo "🛑 停止服务: ./scripts/stop-all.sh" 